
private var _map:Map;
private var _characterManager:CharacterManager;
//public var _level:int = 2;

//private var isSelected:boolean = false;
//private var selectedPlayer:GameCharacter;

//Turn control variables
private var isPlayerTurn:boolean = true;

private var displayEndTurn;

private var displayTextureenemy:Texture;
private var displayTextureplayer:Texture;

//private var startTime:float;
private var ypos:int = 0;
private var ygoup:int = 0;

//In game GUI/Character Select
private var portraitCharacterSelected:Texture2D[] = new Texture2D[5];

//Pause Button
private var textureRatio:float = 1.0;	
private var buttonPauseTexture:Texture2D;
private var buttonPauseHoverTexture:Texture2D;
private var buttonPausePressedTexture:Texture2D;
private var pauseTitleTexture:Texture2D;
private var pausestyle:GUIStyle;
private var pauseMode:boolean;

//Grey screen for pause screen
private var greyTex : Texture2D;

//Game over variables
private var gameover:boolean = false;
private var gameoverTexture:Texture2D;
private var deadflavisTexture:Texture2D;
private var deadpurpuraTexture:Texture2D;

private var buttonResumeTexture:Texture2D;
private var buttonResumeHoverTexture:Texture2D;
private var buttonResumePressedTexture:Texture2D;	
private var resumestyle:GUIStyle;

private var buttonRestartTexture:Texture2D;
private var buttonRestartHoverTexture:Texture2D;
private var buttonRestartPressedTexture:Texture2D;	
private var restartstyle:GUIStyle;

private var buttonExitTexture:Texture2D;
private var buttonExitHoverTexture:Texture2D;
private var buttonExitPressedTexture:Texture2D;	
private var exitstyle:GUIStyle;

private var buttonSound:AudioClip;
private var endTurnSound:AudioClip;

function Start() {
	Time.fixedDeltaTime = 0.05f;
	
	_map = new Map();
	_characterManager = new CharacterManager();
	Level.createLevel( MenuScreen.mapID, _characterManager, _map);
	//Level.createLevel(_level, _characterManager, _map);
	
	displayEndTurn = false;
	
	//End turn
	displayTextureenemy  = Resources.Load("Wooden_Boards_Small");
	displayTextureplayer  = Resources.Load("Wooden_Boards_Small_player");
	displayEndTurn = false;
	ygoup = 2;
	
	//Buttons GUI	
 	buttonPauseTexture = Resources.Load("Buttons/pause_buttonNormal");
 	buttonPauseHoverTexture = Resources.Load("Buttons/pause_buttonHover");
 	buttonPausePressedTexture = Resources.Load("Buttons/pause_buttonPressed");
 	
	buttonRestartTexture = Resources.Load("Buttons/restart_buttonNormal");
 	buttonRestartHoverTexture = Resources.Load("Buttons/restart_buttonHover");
 	buttonRestartPressedTexture = Resources.Load("Buttons/restart_buttonPressed");
 		 	
 	buttonResumeTexture = Resources.Load("Buttons/resume_buttonNormal");
 	buttonResumeHoverTexture = Resources.Load("Buttons/resume_buttonHover");
 	buttonResumePressedTexture = Resources.Load("Buttons/resume_buttonPressed");
 		 	
 	buttonExitTexture = Resources.Load("Buttons/quit_buttonNormal");
 	buttonExitHoverTexture = Resources.Load("Buttons/quit_buttonHover");
 	buttonExitPressedTexture = Resources.Load("Buttons/quit_buttonPressed");	 	
	
	portraitCharacterSelected[0] = Resources.Load("Game/melee_portrait");
	portraitCharacterSelected[1] = Resources.Load("Game/archer_portrait");
	portraitCharacterSelected[2] = Resources.Load("Game/medic_portrait");
	portraitCharacterSelected[3] = Resources.Load("Game/spellcaster_portrait");	
	portraitCharacterSelected[4] = Resources.Load("Game/scout_portrait");	
	
	//Grey Screen
	greyTex = new Texture2D ( 1 , 1 );
    greyTex.SetPixel( 0 , 0 , Color.black );
    greyTex.wrapMode = TextureWrapMode.Repeat;
    greyTex.Apply();
    
    pauseTitleTexture = Resources.Load("Game/pauseTitleTexture");
    
    pausestyle = new GUIStyle();
	pausestyle.normal.background = buttonPauseTexture;
	pausestyle.hover.background = buttonPauseHoverTexture;
	pausestyle.active.background = buttonPausePressedTexture;
	
	restartstyle = new GUIStyle();
	restartstyle.normal.background = buttonRestartTexture;
	restartstyle.hover.background = buttonRestartHoverTexture;
	restartstyle.active.background = buttonRestartPressedTexture;
	
	resumestyle = new GUIStyle();
	resumestyle.normal.background = buttonResumeTexture;
	resumestyle.hover.background = buttonResumeHoverTexture;
	resumestyle.active.background = buttonResumePressedTexture;
	
	exitstyle = new GUIStyle();
	exitstyle.normal.background = buttonExitTexture;
	exitstyle.hover.background = buttonExitHoverTexture;
	exitstyle.active.background = buttonExitPressedTexture;
    
    pauseMode = false;
	
	//Texture ratio
	textureRatio = Screen.width*1.0 / 1920;		
	
	//sound
	buttonSound = Resources.Load("buttonSound");
	endTurnSound = Resources.Load("endTurnSound");
}




function Update()
{	
	if( pauseMode )
	{
		return;
	}

	_map.updateGrid();
	gameLogic();
}

function FixedUpdate ()
{
	if( ygoup == 0 )
	{
		ypos -= 12;
	}
	else if( ygoup == 1 ) 
	{
		ypos += 12;
	}
}

function LateUpdate()
{
	updateFog();
}

function gameLogic()
{
	if( gameover )
		return;

	var end:boolean = true;
	//Player turn
	if (isPlayerTurn)
	{
		//Game over Check
		var enemyList = _characterManager.getEnemies();
		for( i = 0 ; i < enemyList.length ; i++ )
		{
			if( !enemyList[i].getIsDead() )
			{
				end = false;
				break;
			}
		}
		if( end )
			gameOver(1);	
			
		if( !displayEndTurn )
		{
			if(Input.GetKeyDown(KeyCode.Tab))
			{
				_characterManager.setNextSelectedPlayer();
			}
			else if( Input.GetKeyDown(KeyCode.Escape))
			{
				_characterManager.resetSelectedPlayer();
			}
			playerLogic();
		}
		if (_characterManager.isEndOfPlayerTurn() && !displayEndTurn )
		{
			Debug.Log("Player turn ended");
			
			//isPlayerTurn = false;
			DisplayEndTurn();
		}
	}
	//AI turn
	else
	{
		//Game Over Check
		var playerList = _characterManager.getPlayers();		
		for( i = 0; i < playerList.length ; i++ )
		{
			if( !playerList[i].getIsDead() )
			{
				end = false;
				break;
			}
		}
		if( end )
			gameOver(0);
			
		if( !displayEndTurn )
			enemyLogic();
		if (_characterManager.isEndOfEnemyTurn() && !displayEndTurn )
		{
			Debug.Log("Enemy Turn ended");
			 
			//isPlayerTurn = true;
			DisplayEndTurn();
		}
	}
}

function OnGUI()
{
	//if( !displayEndTurn )
	//	return;
	
	var w:float;
	var h:float;
	
	//Game over
	if( gameover )
	{
		//Do a pause so user does not continue playing		
		pauseMode = true;
	
		GUI.color = new Color(1,1,1,0.5);
		GUI.DrawTexture(Rect(0,0,Screen.width,Screen.height), greyTex);
		GUI.color = new Color(1,1,1,1);
		
		w = buttonResumeTexture.width * textureRatio;
		h = buttonResumeTexture.height * textureRatio;
	
		GUI.DrawTexture(Rect(0,-100,gameoverTexture.width*textureRatio,gameoverTexture.height*textureRatio), gameoverTexture);
		
		if (GUI.Button(Rect(Screen.width-2*w,h*2.5,w,h),null,restartstyle))
		{	
			audio.PlayClipAtPoint(buttonSound,Vector3(0,0,0));
			Application.LoadLevel(0);		
		}
		if (GUI.Button(Rect(Screen.width-2*w,h*4,w,h),null,exitstyle))
		{
			audio.PlayClipAtPoint(buttonSound,Vector3(0,0,0));		
			Application.Quit();
		}
		
		var playerList = _characterManager.getPlayers();
		var enemyList = _characterManager.getEnemies();
		var dw = deadflavisTexture.width * textureRatio;
		var dh = deadflavisTexture.height * textureRatio;
		for( var i = 0; i < playerList.length ; i++ )
		{
			if( playerList[i].getIsDead() )
			{
				GUI.DrawTexture(Rect((i*dw+2.2*w)*0.5,h*2.7,dw,dh),deadflavisTexture);
			}
		}
		for( i = 0 ; i < enemyList.length ; i++ )
		{
			if( enemyList[i].getIsDead() )
			{
				if( i <= 11 )
					GUI.DrawTexture(Rect((i*dw+2.2*w)*0.5,h*4,dw,dh),deadpurpuraTexture);
				else
					GUI.DrawTexture(Rect(((i-12)*dw+2.2*w)*0.5,h*4.5,dw,dh),deadpurpuraTexture);				
			}
		}
		
		return;
	}
	if( pauseMode )
	{
		GUI.color = new Color(1,1,1,0.5);
		GUI.DrawTexture(Rect(0,0,Screen.width,Screen.height), greyTex);
		
		GUI.color = new Color(1,1,1,1);
		
		w = buttonResumeTexture.width * textureRatio;
		h = buttonResumeTexture.height * textureRatio;
		
		GUI.DrawTexture(Rect(Screen.width/2-(pauseTitleTexture.width*textureRatio/2),h,pauseTitleTexture.width*textureRatio,pauseTitleTexture.height*textureRatio), pauseTitleTexture);
		
		if (GUI.Button(Rect(Screen.width/2-w/2,h*3,w,h),null,resumestyle))
		{
			//gameOver(1); //TEMP
			audio.PlayClipAtPoint(buttonSound,Vector3(0,0,0));
			_characterManager.setPauseMode(false);
			pauseMode = false;
		}
		if (GUI.Button(Rect(Screen.width/2-w/2,h*4.5,w,h),null,restartstyle))
		{	
			audio.PlayClipAtPoint(buttonSound,Vector3(0,0,0));
			Application.LoadLevel(0);		
		}
		if (GUI.Button(Rect(Screen.width/2-w/2,h*6,w,h),null,exitstyle))
		{
			audio.PlayClipAtPoint(buttonSound,Vector3(0,0,0));		
			Application.Quit();
		}
			
		return;
	}
	
	//Display the bottom left character selected portrait
	if( _characterManager.getSelectedPlayer() != null )
	{
	    var type = _characterManager.getSelectedPlayer().getPlayerType();
		
		w = portraitCharacterSelected[0].width*textureRatio;
		h = portraitCharacterSelected[0].height*textureRatio;
	
		GUI.DrawTexture(Rect(0,Screen.height-h,w,h), portraitCharacterSelected[type]);
	}
	
	//Pause button
	w = buttonPauseTexture.width * textureRatio;
	h = buttonPauseTexture.height * textureRatio;
	if (GUI.Button(Rect(Screen.width-w,5,w,h),null,pausestyle))
	{
		audio.PlayClipAtPoint(buttonSound,Vector3(0,0,0));	
		_characterManager.setPauseMode(true);
		pauseMode = true;
	}

	//End turn GUI
	if (displayEndTurn && isPlayerTurn)
	{
		GUI.DrawTexture(Rect(Screen.width/2-250,ypos,500,604), displayTextureenemy);
		//GUI.Box (Rect(0,0,800,966), GUIContent(displayTexture));
		//GUI.Label(Rect(Screen.width/2-200, Screen.height/2, 400, 100),"ENEMY TURN",fontstyleEndTurn);
	}
	else if( displayEndTurn && !isPlayerTurn )
	{
		GUI.DrawTexture(Rect(Screen.width/2-250,ypos,500,604), displayTextureplayer);
      	//GUI.Label(Rect(Screen.width/2-200, Screen.height/2, 400, 100),"PLAYER TURN",fontstyleEndTurn);  
	}		
}

private function DisplayEndTurn() {
	displayEndTurn = true;
	ygoup = 1;
	ypos = -604;			
	audio.PlayClipAtPoint(endTurnSound,Vector3(0,0,0), 0.5f);
    yield WaitForSeconds(2);

    ygoup = 2;
    yield WaitForSeconds(1);
    
    ygoup = 0;
    audio.PlayClipAtPoint(endTurnSound,Vector3(0,0,0), 0.5f);
    yield WaitForSeconds(2);
    
    ygoup = 2;
    displayEndTurn = false;
    if( isPlayerTurn )
    {
        isPlayerTurn = false; 
    	_characterManager.resetEnemyTurn();
    	_characterManager.setAImoveDone(false);
    }
    else
    {
    	isPlayerTurn = true;
    	_characterManager.resetTurn();
    }
}

function enemyLogic()
{
	_characterManager.updateEnemy();
}

function playerLogic()
{
	_characterManager.updateCharacter(_map.getAndClearSelectedTile());
}

function gameOver(type:int)
{
	var endgameSound:AudioClip;
	gameover = true;
	//Player lose
	if( type == 0 )
	{
		endgameSound = Resources.Load("loseGameSound");
	    audio.PlayClipAtPoint(endgameSound,Vector3(0,0,0));
		gameoverTexture = Resources.Load("Game/loseScreen");
	}
	//Player win
	else 
	{
		endgameSound = Resources.Load("winGameSound");
		gameoverTexture = Resources.Load("Game/winScreen");
	}
	
	audio.PlayClipAtPoint(endgameSound,Vector3(0,0,0));
	deadflavisTexture = Resources.Load("Game/flavis_icon");
	deadpurpuraTexture = Resources.Load("Game/purpura_icon");
}

function updateFog()
{
	if(_characterManager.getPlayers()!=null)
		_map.updateFog(_characterManager.getPlayers());
}

	/*var tile:Tile = null;  //reference to the tile mouse overed
	
	var hit : RaycastHit;
	var ray : Ray;
	ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	if ( Physics.Raycast( ray, hit, 100 ) )
	{
		//if raycast hit Tile
		if (hit.collider.gameObject.tag.Equals("Tile"))
			tile = hit.collider.gameObject.GetComponent(Tile);
		//if raycast hits a player
		else if (hit.collider.gameObject.tag.Equals("PlayerCharacter"))
			tile = hit.collider.gameObject.GetComponent(GameCharacter).getTileReference();

		if (tile == null)
			return;
		
		//check if player action allowed
		if (_characterManager.isMoveDone())
		{
			//check if theres a tile reference and check for clicks
			if (Input.GetButtonDown("Fire1"))
			{
				//if character not selected
				if (!isSelected)
				{  
					//if there is player on the tile
					if (tile.isOccupied() && tile.getCharacter().isPlayer())
					{
						if (!tile.getCharacter().ReturnIsDone())
						{
							Debug.Log("Character selected");
							selectedPlayer = tile.getCharacter();
							//select character
							selectedPlayer.Selected();
							isSelected = true;		
						}
					}
				}
				else //if character selected
				{
					if (tile.getCoord() == selectedPlayer.getCoord())
					{
						//clicked on same place
						//ignore
						Debug.Log("Click on self");
					}
					//if clicked on another character
					else if (tile.isOccupied() && tile.getCharacter().isPlayer() )
					{
						if (!tile.getCharacter().ReturnIsDone())
						{
							Debug.Log("Click on another character");
							selectedPlayer.Deselected();
							selectedPlayer = tile.getCharacter();
							//select character
							selectedPlayer.Selected();
							isSelected = true;		
						}
					}
					//if selected tile is within moving range
					else if (selectedPlayer.isWithinMoveRange(tile))
					{
						Debug.Log("Move to tile");
						//move to tile
						selectedPlayer.moveTo(tile);
						_characterManager.setMoveDone(false);
						isSelected = false;
					}
					//invalid selection
					else
					{
						Debug.Log("Invalid");
						//unselect character
						selectedPlayer.Deselected();
						isSelected = false;
					}
				}
			}
		}
		
   }*/